// @ts-check
import path, { dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { defineConfig } from "@rspack/cli";
import { rspack } from "@rspack/core";
import { ReactRefreshRspackPlugin } from "@rspack/plugin-react-refresh";
const resolve = (/** @type {string} */ dir) => path.resolve(__dirname, dir);
const __dirname = dirname(fileURLToPath(import.meta.url));
const isDev = process.env.NODE_ENV === "development";

// Target browsers, see: https://github.com/browserslist/browserslist
const targets = ["last 2 versions", "> 0.2%", "not dead", "Firefox ESR"];

export default defineConfig(() => {
  return {
    context: __dirname,
    entry: {
      main: "./src/main.jsx",
    },
    resolve: {
      alias: {
        "@": resolve("./src"), // 这样配置后 @ 可以指向 src 目录
      },
      extensions: ["...", ".ts", ".tsx", ".jsx"],
    },
    module: {
      rules: [
        {
          test: /\.svg$/,
          type: "asset",
        },
        {
          test: /\.(jsx?|tsx?)$/,
          use: [
            {
              loader: "builtin:swc-loader",
              options: {
                jsc: {
                  parser: {
                    syntax: "typescript",
                    tsx: true,
                  },
                  transform: {
                    react: {
                      runtime: "automatic",
                      development: isDev,
                      refresh: isDev,
                    },
                  },
                },
                env: { targets },
              },
            },
          ],
        },
        {
          test: /\.module\.less$/,
          use: [
            {
              loader: "css-loader",
              options: {
                modules: {
                  localIdentName: "[name]__[local]--[hash:base64:5]",
                  exportLocalsConvention: "camelCase",
                  namedExport: false, // 禁用命名导出，使用默认导出
                  exportOnlyLocals: false,
                },
              },
            },
            {
              loader: "less-loader",
              options: {
                // less 配置选项
                lessOptions: {
                  javascriptEnabled: true,
                  // 其他 less 配置
                },
              },
            },
          ],
          type: "css/auto", // 重要：这表示使用 CSS Modules
        },
        // 普通 less 文件配置（非 CSS Modules）
        {
          test: /\.less$/,
          exclude: /\.module\.less$/,
          use: ["css-loader", "less-loader"],
          type: "css",
        },
      ],
    },
    plugins: [
      new rspack.HtmlRspackPlugin({
        template: "./index.html",
      }),
      isDev ? new ReactRefreshRspackPlugin() : null,
    ],
    optimization: {
      minimizer: [
        new rspack.SwcJsMinimizerRspackPlugin(),
        new rspack.LightningCssMinimizerRspackPlugin({
          minimizerOptions: { targets },
        }),
      ],
    },
    experiments: {
      css: true,
    },
  };
});
